"""权限管理模块序列化器 - 使用Django内建权限系统"""
from rest_framework import serializers
from django.contrib.auth.models import User, Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.utils import timezone
from .models import PermissionCategory, GroupProfile, PermissionProfile, UserGroupAssignment


class PermissionCategorySerializer(serializers.ModelSerializer):
    """权限分类序列化器"""
    permission_count = serializers.SerializerMethodField(help_text="权限数量")

    class Meta:
        model = PermissionCategory
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']

    def get_permission_count(self, obj) -> int:
        """获取权限数量"""
        return obj.permissions.count()


class PermissionProfileSerializer(serializers.ModelSerializer):
    """权限扩展信息序列化器"""
    permission_codename = serializers.CharField(source='permission.codename', read_only=True, help_text="权限代码名")
    permission_name = serializers.CharField(source='permission.name', read_only=True, help_text="权限名称")
    content_type_name = serializers.CharField(source='permission.content_type.name', read_only=True, help_text="内容类型")
    app_label = serializers.CharField(source='permission.content_type.app_label', read_only=True, help_text="应用标签")
    category_name = serializers.CharField(source='category.display_name', read_only=True, help_text="分类名称")

    class Meta:
        model = PermissionProfile
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at']


class PermissionSerializer(serializers.ModelSerializer):
    """Django内建权限序列化器"""
    profile = PermissionProfileSerializer(read_only=True, help_text="扩展信息")
    content_type_name = serializers.CharField(source='content_type.name', read_only=True, help_text="内容类型")
    app_label = serializers.CharField(source='content_type.app_label', read_only=True, help_text="应用标签")

    class Meta:
        model = Permission
        fields = '__all__'
        read_only_fields = ['id']


class PermissionListSerializer(serializers.ModelSerializer):
    """权限列表序列化器"""
    profile = PermissionProfileSerializer(read_only=True, help_text="扩展信息")
    content_type_name = serializers.CharField(source='content_type.name', read_only=True, help_text="内容类型")
    app_label = serializers.CharField(source='content_type.app_label', read_only=True, help_text="应用标签")
    category_name = serializers.CharField(source='profile.category.display_name', read_only=True, help_text="分类名称")

    class Meta:
        model = Permission
        fields = '__all__'
        read_only_fields = ['id']


class GroupProfileSerializer(serializers.ModelSerializer):
    """组扩展信息序列化器"""
    group_name = serializers.CharField(source='group.name', read_only=True, help_text="组名")
    created_by_name = serializers.CharField(source='created_by.username', read_only=True, help_text="创建者用户名")

    class Meta:
        model = GroupProfile
        fields = '__all__'
        read_only_fields = ['id', 'created_at', 'updated_at', 'created_by']


class GroupSerializer(serializers.ModelSerializer):
    """Django内建组序列化器"""
    profile = GroupProfileSerializer(read_only=True, help_text="扩展信息")
    permission_count = serializers.SerializerMethodField(help_text="权限数量")
    user_count = serializers.SerializerMethodField(help_text="用户数量")

    class Meta:
        model = Group
        fields = '__all__'
        read_only_fields = ['id']

    def get_permission_count(self, obj) -> int:
        """获取权限数量"""
        return obj.permissions.count()

    def get_user_count(self, obj) -> int:
        """获取用户数量"""
        return obj.user_set.count()


class GroupListSerializer(serializers.ModelSerializer):
    """组列表序列化器"""
    profile = GroupProfileSerializer(read_only=True, help_text="扩展信息")
    permission_count = serializers.SerializerMethodField(help_text="权限数量")
    user_count = serializers.SerializerMethodField(help_text="用户数量")
    display_name = serializers.CharField(source='profile.display_name', read_only=True, help_text="显示名称")
    description = serializers.CharField(source='profile.description', read_only=True, help_text="描述")
    is_system = serializers.BooleanField(source='profile.is_system', read_only=True, help_text="是否为系统组")

    class Meta:
        model = Group
        fields = '__all__'
        read_only_fields = ['id']

    def get_permission_count(self, obj) -> int:
        """获取权限数量"""
        return obj.permissions.count()

    def get_user_count(self, obj) -> int:
        """获取用户数量"""
        return obj.user_set.count()


class GroupDetailSerializer(serializers.ModelSerializer):
    """组详情序列化器"""
    profile = GroupProfileSerializer(read_only=True, help_text="扩展信息")
    permissions = PermissionListSerializer(many=True, read_only=True, help_text="组权限")
    permission_count = serializers.SerializerMethodField(help_text="权限数量")
    user_count = serializers.SerializerMethodField(help_text="用户数量")

    class Meta:
        model = Group
        fields = '__all__'
        read_only_fields = ['id']

    def get_permission_count(self, obj) -> int:
        """获取权限数量"""
        return obj.permissions.count()

    def get_user_count(self, obj) -> int:
        """获取用户数量"""
        return obj.user_set.count()


class UserGroupAssignmentSerializer(serializers.ModelSerializer):
    """用户组分配记录序列化器"""
    user_name = serializers.CharField(source='user.username', read_only=True, help_text="用户名")
    group_name = serializers.CharField(source='group.name', read_only=True, help_text="组名")
    group_display_name = serializers.CharField(source='group.profile.display_name', read_only=True, help_text="组显示名称")
    assigned_by_name = serializers.CharField(source='assigned_by.username', read_only=True, help_text="分配者用户名")
    is_expired = serializers.SerializerMethodField(help_text="是否过期")

    class Meta:
        model = UserGroupAssignment
        fields = '__all__'
        read_only_fields = ['id', 'assigned_at', 'assigned_by']

    def get_is_expired(self, obj) -> bool:
        """检查是否过期"""
        if obj.expires_at:
            return timezone.now() > obj.expires_at
        return False


class AssignGroupSerializer(serializers.Serializer):
    """分配组序列化器"""
    user_ids = serializers.ListField(
        child=serializers.IntegerField(),
        help_text="用户ID列表"
    )
    expires_at = serializers.DateTimeField(
        required=False,
        allow_null=True,
        help_text="过期时间"
    )
    notes = serializers.CharField(
        required=False,
        allow_blank=True,
        help_text="备注"
    )

    def validate_user_ids(self, value):
        """验证用户ID"""
        if not value:
            raise serializers.ValidationError("用户ID列表不能为空")

        # 检查用户是否存在
        existing_users = User.objects.filter(id__in=value).values_list('id', flat=True)
        missing_users = set(value) - set(existing_users)
        if missing_users:
            raise serializers.ValidationError(f"用户ID不存在: {list(missing_users)}")

        return value


class AssignPermissionSerializer(serializers.Serializer):
    """分配权限序列化器"""
    permission_ids = serializers.ListField(
        child=serializers.IntegerField(),
        help_text="权限ID列表"
    )

    def validate_permission_ids(self, value):
        """验证权限ID"""
        if not value:
            raise serializers.ValidationError("权限ID列表不能为空")

        # 检查权限是否存在
        existing_permissions = Permission.objects.filter(id__in=value).values_list('id', flat=True)
        missing_permissions = set(value) - set(existing_permissions)
        if missing_permissions:
            raise serializers.ValidationError(f"权限ID不存在: {list(missing_permissions)}")

        return value


class UserPermissionSerializer(serializers.Serializer):
    """用户权限序列化器"""
    user_id = serializers.IntegerField(help_text="用户ID")
    permissions = serializers.ListField(
        child=serializers.CharField(),
        read_only=True,
        help_text="权限列表"
    )
    groups = serializers.ListField(
        child=serializers.CharField(),
        read_only=True,
        help_text="组列表"
    )


class GroupStatusSerializer(serializers.Serializer):
    """组状态序列化器"""
    is_active = serializers.BooleanField(help_text="是否激活")


class CreateGroupSerializer(serializers.Serializer):
    """创建组序列化器"""
    name = serializers.CharField(max_length=150, help_text="组名")
    display_name = serializers.CharField(max_length=100, help_text="显示名称")
    description = serializers.CharField(required=False, allow_blank=True, help_text="描述")
    is_system = serializers.BooleanField(default=False, help_text="是否为系统组")

    def validate_name(self, value):
        """验证组名"""
        if Group.objects.filter(name=value).exists():
            raise serializers.ValidationError("组名已存在")
        return value


class GroupUserListSerializer(serializers.ModelSerializer):
    """组用户列表序列化器 - 用于组用户管理"""
    full_name = serializers.SerializerMethodField(help_text="全名")
    groups_count = serializers.SerializerMethodField(help_text="所属组数量")
    groups_display = serializers.SerializerMethodField(help_text="所属组显示")
    last_login_display = serializers.SerializerMethodField(help_text="最后登录时间显示")
    status_display = serializers.SerializerMethodField(help_text="状态显示")

    class Meta:
        model = User
        # 🔑 关键：明确列出字段以确保SerializerMethodField被包含在API Schema中
        fields = [
            'id', 'username', 'email', 'first_name', 'last_name', 'full_name',
            'is_active', 'is_staff', 'is_superuser', 'date_joined', 'last_login',
            'groups_count', 'groups_display', 'last_login_display', 'status_display'
        ]
        read_only_fields = ['id', 'date_joined', 'last_login']

    def get_full_name(self, obj) -> str:
        """获取全名"""
        if obj.last_name and obj.first_name:
            return f"{obj.last_name}{obj.first_name}"
        elif obj.first_name:
            return obj.first_name
        elif obj.last_name:
            return obj.last_name
        return obj.username

    def get_groups_count(self, obj) -> int:
        """获取用户所属组数量"""
        return obj.groups.count()

    def get_groups_display(self, obj) -> str:
        """获取所属组显示"""
        group_names = list(obj.groups.values_list('name', flat=True))
        if not group_names:
            return "无"
        elif len(group_names) <= 3:
            return ", ".join(group_names)
        else:
            return f"{', '.join(group_names[:3])} 等{len(group_names)}个组"

    def get_last_login_display(self, obj) -> str:
        """获取最后登录时间显示"""
        if obj.last_login:
            return obj.last_login.strftime('%Y-%m-%d %H:%M:%S')
        return "从未登录"

    def get_status_display(self, obj) -> str:
        """获取状态显示"""
        if obj.is_superuser:
            return "超级管理员"
        elif obj.is_staff:
            return "管理员"
        elif obj.is_active:
            return "正常用户"
        else:
            return "已禁用"


class RemoveUsersFromGroupSerializer(serializers.Serializer):
    """从组中移除用户序列化器"""
    user_ids = serializers.ListField(
        child=serializers.IntegerField(),
        help_text="要移除的用户ID列表"
    )

    def validate_user_ids(self, value):
        """验证用户ID"""
        if not value:
            raise serializers.ValidationError("用户ID列表不能为空")

        # 检查用户是否存在
        existing_users = User.objects.filter(id__in=value)
        if existing_users.count() != len(value):
            missing_ids = set(value) - set(existing_users.values_list('id', flat=True))
            raise serializers.ValidationError(f"用户ID不存在: {list(missing_ids)}")

        return value
